package com.sunday.pinxinghui.model.lifecircle;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.CommonAdapter;
import com.sunday.pinxinghui.adapter.ProductListAdapter;
import com.sunday.pinxinghui.adapter.ViewHolder;
import com.sunday.pinxinghui.entity.LifeData;
import com.sunday.pinxinghui.entity.Product;
import com.sunday.pinxinghui.model.products.ProductClassifyFragment;
import com.sunday.pinxinghui.network.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Author by Damon,  on 2017/11/30.
 */

public class SearchShopActivity extends BaseActivity {

    @Bind(R.id.edit_query)
    EditText editQuery;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;


    private LinearLayoutManager layoutManager;
    private CommonAdapter<LifeData.ShopsBean> adapter;
    private List<LifeData.ShopsBean> dataSet = new ArrayList<>();
    private int pageNo = 1, lastVisibleItem;
    private boolean isCanloadMore;
    private String keyWord;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_shop);
        ButterKnife.bind(this);
        initQuery();
        initRecyclerView();
        getData();
    }

    private void initQuery() {
        editQuery.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyWord = editQuery.getText().toString().trim();
                pageNo = 1;
                getData();

            }
        });

    }

    private void initRecyclerView() {
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<LifeData.ShopsBean>(mContext, R.layout.list_life_shop_item, dataSet) {
            @Override
            public void convert(ViewHolder holder, final LifeData.ShopsBean item, int position) {
                ImageView imgView = holder.getView(R.id.shop_img);
                Glide.with(mContext)
                        .load(item.getImage())
                        .error(R.mipmap.ic_default)
                        .into(imgView);
                ((TextView) holder.getView(R.id.shop_title)).setText(item.getName());
                ((TextView) holder.getView(R.id.shop_desc)).setText(item.getDesc());
                ((TextView) holder.getView(R.id.shop_addr)).setText("【" + item.getArea() + "】");
                holder.setOnClickListener(R.id.layout, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        intent = new Intent(mContext, ShopDetailActivity.class);
                        intent.putExtra("shopId", item.getId());
                        startActivity(intent);
                    }
                });

            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                getData();
            }
        });
    }

    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<List<LifeData.ShopsBean>>> call = ApiClient.getApiAdapter().getShopByLifeCatId(null, pageNo, Constants.PAGE_SIZE, keyWord);
        call.enqueue(new Callback<ResultDO<List<LifeData.ShopsBean>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<LifeData.ShopsBean>>> call, Response<ResultDO<List<LifeData.ShopsBean>>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                ptrFrame.refreshComplete();
                ResultDO<List<LifeData.ShopsBean>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }

                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    if (resultDO.getResult().size() == Constants.PAGE_SIZE) {
                        isCanloadMore = true;
                        pageNo++;
                    } else {
                        isCanloadMore = false;
                    }
                    dataSet.addAll(resultDO.getResult());
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<LifeData.ShopsBean>>> call, Throwable t) {
                dissMissDialog();
                ptrFrame.refreshComplete();
            }
        });
    }

    @OnClick(R.id.btn_back)
    void onclick() {
        finish();
    }

}
